#!/usr/bin/env python
# -*- coding: utf-8 -*-

from gm.api import get_history_symbol, set_token, get_symbols, history
from gm.enum import ADJUST_PREV

from web.api.base_api import BaseApi
from web.constants.python_api_result import PythonApiResult
from web.manager.log_manager import LogManager
from web.models.etf_transaction_data import EtfTransactionData

Logger = LogManager.get_logger(__name__)


class EtfTransactionDataApi(BaseApi):
    """
    ETF数据api
    """

    def write_etf_transaction_data_by_date(self, begin_date, end_date):
        """
        调用akshare接口，根据开始时间和结束时间保存ETF数据
        """

        # set_token(MyQuantConfig.MyQuant_Token)

        etf_info_list = self.etf_info_service.find_all()

        if etf_info_list is not None and len(etf_info_list) > 0:
            for etf_info in etf_info_list:
                prefix_code = etf_info.code_[0:2]
                _code = None
                if prefix_code == 'SH':
                    _code = 'SHSE.' + etf_info.code_[2:]
                if prefix_code == 'SZ':
                    _code = 'SZSE.' + etf_info.code_[2:]
                result_list = history(symbol=_code, frequency='1d', start_time=begin_date,  end_time=end_date, fields='eob, open, last_close, close, low, high, amount, volume', adjust=ADJUST_PREV, df= False)

                # 插入记录
                etf_transaction_data_list = list()
                if result_list is not None and len(result_list) > 0:
                    for result in result_list:
                        dict_values = result#.values().mapping
                        etf_transaction_data = EtfTransactionData()
                        etf_transaction_data.code_= etf_info.code_[2:]
                        etf_transaction_data.date_ = dict_values['eob']
                        etf_transaction_data.open_price = dict_values['open']
                        etf_transaction_data.highest_price = dict_values['high']
                        etf_transaction_data.lowest_price = dict_values['low']
                        etf_transaction_data.close_price = dict_values['close']
                        etf_transaction_data.volume = dict_values['volume']
                        etf_transaction_data.turnover = dict_values['amount']
                        etf_transaction_data_list.append(etf_transaction_data)
                    self.etf_transaction_data_service.batch_insert(etf_transaction_data_list)
        print(PythonApiResult.FINISH)

    # def write_etf_transaction_data_by_date(self, begin_date, end_date):
    #     """
    #     调用akshare接口，根据开始时间和结束时间查询ETF数据
    #     """
    #
    #     etf_transaction_data_list = list()
    #
    #     code_list = self.etf_transaction_data_service.find_code()
    #     if code_list is not None and len(code_list) > 0:
    #         sohu_num = 0
    #         fund_etf_hist_em_df_num = 0
    #         stock_zh_a_hist_df_num = 0
    #         fund_etf_fund_info_em_df_num = 0
    #         fund_etf_hist_em_df_not_pass_num = 0
    #         stock_zh_a_hist_df_not_pass_num = 0
    #         fund_etf_fund_info_em_df_not_pass_num = 0
    #         not_pass_num = 0
    #
    #         for code in code_list:
    #             code = code[2:]
    #
    #             try:
    #                 url = 'https://q.stock.sohu.com/hisHq?code=cn_' + code + '&start=' + begin_date + '&end=' + end_date + '&stat=1&order=D&period=d'
    #                 res = requests.get(url)
    #                 res.encoding = 'gbk'
    #                 json_data_list = json.loads(res.text)
    #                 if len(json_data_list) != 0 and json_data_list[0]['status'] == 0:
    #                     # 插入记录
    #                     for json_data in json_data_list:
    #                         etf_transaction_data = EtfTransactionData()
    #                         etf_transaction_data.code_ = code
    #                         etf_transaction_data.date_ = json_data['hq'][0][0]
    #                         etf_transaction_data.open_price = json_data['hq'][0][1]
    #                         etf_transaction_data.close_price = json_data['hq'][0][2]
    #                         etf_transaction_data.change_amount = json_data['hq'][0][3]
    #                         etf_transaction_data.change_range = json_data['hq'][0][4]
    #                         etf_transaction_data.lowest_price = json_data['hq'][0][5]
    #                         etf_transaction_data.volume = json_data['hq'][0][6]
    #                         etf_transaction_data.turnover = json_data['hq'][0][7]
    #                         etf_transaction_data_list.append(etf_transaction_data)
    #                     continue
    #             except Exception as e:
    #                 # Logger.error('sohu_df[' + code + ']报错')
    #                 # fund_etf_hist_em_df_not_pass_num = fund_etf_hist_em_df_not_pass_num + 1
    #                 pass
    #
    #             try:
    #                 fund_etf_hist_em_df = ak.fund_etf_hist_em(symbol=code, period="daily", start_date=begin_date,
    #                                                           end_date=end_date, adjust="")
    #                 if len(fund_etf_hist_em_df) != 0:
    #                     # 插入记录
    #                     fund_etf_hist_em_df_num = fund_etf_hist_em_df_num + 1
    #                     continue
    #             except Exception as e:
    #                 Logger.error('fund_etf_hist_em_df[' + code + ']报错')
    #                 fund_etf_hist_em_df_not_pass_num = fund_etf_hist_em_df_not_pass_num + 1
    #
    #             try:
    #                 stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=code, period="daily", start_date=begin_date,
    #                                                         end_date=end_date, adjust="")
    #                 if len(stock_zh_a_hist_df) != 0:
    #                     # 插入记录
    #                     stock_zh_a_hist_df_num = stock_zh_a_hist_df_num + 1
    #                     continue
    #             except Exception as e:
    #                 Logger.error('fund_etf_hist_em_df[' + code + ']报错')
    #                 stock_zh_a_hist_df_not_pass_num = stock_zh_a_hist_df_not_pass_num + 1
    #
    #             try:
    #                 fund_etf_fund_info_em_df = ak.fund_etf_fund_info_em(fund=code, start_date=begin_date,
    #                                                                     end_date=end_date)
    #                 if len(fund_etf_fund_info_em_df) != 0:
    #                     # 插入记录
    #                     etf_transaction_data = EtfTransactionData()
    #                     etf_transaction_data.code_ = code
    #                     etf_transaction_data.date_ = fund_etf_fund_info_em_df['净值日期']
    #                     etf_transaction_data_list.append(etf_transaction_data)
    #             except Exception as e:
    #                 # Logger.error('fund_etf_fund_info_em_df[' + code + ']报错')
    #                 # fund_etf_fund_info_em_df_not_pass_num = fund_etf_fund_info_em_df_not_pass_num + 1
    #                 pass
    #
    #             Logger.warning('ETF[' + code + ']没有数据')
    #             not_pass_num = not_pass_num + 1
    #
    #         # Logger.warning(fund_etf_hist_em_df_num)
    #         # Logger.warning(stock_zh_a_hist_df_num)
    #         # Logger.warning(fund_etf_fund_info_em_df_num)
    #         # Logger.warning(fund_etf_hist_em_df_num + stock_zh_a_hist_df_num + fund_etf_fund_info_em_df_num)
    #         # Logger.warning(fund_etf_hist_em_df_not_pass_num)
    #         # Logger.warning(stock_zh_a_hist_df_not_pass_num)
    #         # Logger.warning(fund_etf_fund_info_em_df_not_pass_num)
    #         # Logger.warning(not_pass_num)
    #         # Logger.warning(fund_etf_hist_em_df_not_pass_num + stock_zh_a_hist_df_not_pass_num +
    #         #                fund_etf_fund_info_em_df_not_pass_num + not_pass_num)
    #
    #     print(etf_transaction_data_list)